package com.edu.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.edu.admin.entity.SysUser;
import com.edu.admin.enums.ExceptionEnum;
import com.edu.admin.enums.UseTypeEnum;
import com.edu.admin.service.SchoolService;
import com.edu.admin.service.UserService;
import com.edu.admin.common.RestResult;
import com.edu.admin.vo.UserVo;
import com.github.pagehelper.PageInfo;

/**
 * 学生管理
 *  
 * @author Wangjiong
 * 
 */
@RestController
@RequestMapping(value = "/student", name = "学生管理")
public class StudentController {
	//private static final Logger log = LoggerFactory.getLogger(StudentController.class);
	@Autowired
	private UserService	userService;
	@Autowired
	private SchoolService schoolService;
	
	/**
     * 获取学生列表
     * 
	 * @apiGroup student
	 * @api {get} /student/listAllStudentPage 获取学生列表
	 * @apiVersion 1.0.0
	 * @apiName getStudentListBySchoolName
	 *
	 * @apiParam {String} schoolName 学校名称  required = false
	 * @apiParam {String} userName 学生姓名  required = false
	 * @apiParam {String} account 学生账号  required = false
	 * @apiParam {Integer} isGraduated 是否毕业  required = false
	 * @apiParam {Integer} pageNum 页码  required = false
	 * @apiParam {Integer} pageSize 每页记录数  required = false
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "total": 2,
		        "list": [
		            {
		                "userId": 13,
		                "account": "1234567",
		                "userName": "学生03",
		                "pinyin": null,
		                "phone": "",
		                "phaseId": 2,
		                "schoolId": 1,
		                "classesId": 0,
		                "birthday": "",
		                "gender": "0",
		                "type": 2,
		                "imageUrl": null,
		                "provinceCode": "110000",
		                "cityCode": "110100",
		                "districtCode": "110105",
		                "address": null,
		                "roleId": null,
		                "intro": null,
		                "studentNo": "1234567",
		                "teacherNo": null,
		                "openid": null,
		                "point": null,
		                "userRemark": null,
		                "useType": 0,
		                "schoolName": "测试学校",
		                "classesName": null,
		                "gradeId": null,
		                "gradeName": null,
		                "phaseName": "初中",
		                "provinceName": "北京市",
		                "cityName": "市辖区",
		                "districtName": "朝阳区",
		                "subjects": null,
		                "roleName": null
		            },
		            {
		                "userId": 3,
		                "account": "2222",
		                "userName": "学生2",
		                "pinyin": null,
		                "phone": "13701234567",
		                "phaseId": 2,
		                "schoolId": 8,
		                "classesId": 0,
		                "birthday": null,
		                "gender": "1",
		                "type": 2,
		                "imageUrl": null,
		                "provinceCode": "110000",
		                "cityCode": "110100",
		                "districtCode": "110102",
		                "address": null,
		                "roleId": 4,
		                "intro": null,
		                "studentNo": "2222",
		                "teacherNo": null,
		                "openid": null,
		                "point": null,
		                "userRemark": null,
		                "useType": 1,
		                "schoolName": "测试学校8",
		                "classesName": null,
		                "gradeId": null,
		                "gradeName": null,
		                "phaseName": "初中",
		                "provinceName": "北京市",
		                "cityName": "市辖区",
		                "districtName": "西城区",
		                "subjects": null,
		                "roleName": "校长"
		            }
		        ],
		        "pageNum": 1,
		        "pageSize": 10,
		        "size": 2,
		        "startRow": 1,
		        "endRow": 2,
		        "pages": 1,
		        "prePage": 0,
		        "nextPage": 0,
		        "isFirstPage": true,
		        "isLastPage": true,
		        "hasPreviousPage": false,
		        "hasNextPage": false,
		        "navigatePages": 8,
		        "navigatepageNums": [
		            1
		        ],
		        "navigateFirstPage": 1,
		        "navigateLastPage": 1,
		        "firstPage": 1,
		        "lastPage": 1
		    }
		}
	 *
	 *
	 */
    @RequestMapping(value = "listAllStudentPage", name = "学生列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/student/listAllStudentPage')")
    public RestResult getStudentListBySchoolName(@RequestParam(name = "schoolName", required = false) String schoolName,
    		@RequestParam(name = "userName", required = false) String userName,
    		@RequestParam(name = "account", required = false) String account,
    		@RequestParam(value = "isGraduated", required = false) Integer isGraduated,
    		@RequestParam(name = "pageNum", required = false) Integer pageNum,
			@RequestParam(name = "pageSize", required = false) Integer pageSize)
    		throws Exception {
    	
    	PageInfo<UserVo> pageInfo = userService.getStudentListBySchoolName(pageNum, pageSize,schoolName,userName,account,isGraduated);
        
        return RestResult.ok(pageInfo);
    }
    
    /**
     * 获取学生列表
     * 
	 * @apiGroup student
	 * @api {get} /student/listAllSchoolStudentPage 获取学生列表
	 * @apiVersion 1.0.0
	 * @apiName getStudentListByClassesId
	 *
	 * @apiParam {Long} schoolId 学校id  required = false
	 * @apiParam {Long} phaseId 学段id  required = false
	 * @apiParam {Long} gradeId 年级id required = false
	 * @apiParam {Long} classesId 班级id  required = false
	 * @apiParam {String} userName 学生姓名  required = false
	 * @apiParam {String} account 学生账号  required = false
	 * @apiParam {Integer} isGraduated 是否毕业  required = false
	 * @apiParam {Integer} pageNum 页码  required = false
	 * @apiParam {Integer} pageSize 每页记录数  required = false
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "total": 2,
		        "list": [
		            {
		                "userId": 13,
		                "account": "1234567",
		                "userName": "学生03",
		                "pinyin": null,
		                "phone": "",
		                "phaseId": 2,
		                "schoolId": 1,
		                "classesId": 0,
		                "birthday": "",
		                "gender": "0",
		                "type": 2,
		                "imageUrl": null,
		                "provinceCode": "110000",
		                "cityCode": "110100",
		                "districtCode": "110105",
		                "address": null,
		                "roleId": null,
		                "intro": null,
		                "studentNo": "1234567",
		                "teacherNo": null,
		                "openid": null,
		                "point": null,
		                "userRemark": null,
		                "useType": 0,
		                "schoolName": "测试学校",
		                "classesName": null,
		                "gradeId": null,
		                "gradeName": null,
		                "phaseName": "初中",
		                "provinceName": "北京市",
		                "cityName": "市辖区",
		                "districtName": "朝阳区",
		                "subjects": null,
		                "roleName": null
		            },
		            {
		                "userId": 3,
		                "account": "2222",
		                "userName": "学生2",
		                "pinyin": null,
		                "phone": "13701234567",
		                "phaseId": 2,
		                "schoolId": 8,
		                "classesId": 0,
		                "birthday": null,
		                "gender": "1",
		                "type": 2,
		                "imageUrl": null,
		                "provinceCode": "110000",
		                "cityCode": "110100",
		                "districtCode": "110102",
		                "address": null,
		                "roleId": 4,
		                "intro": null,
		                "studentNo": "2222",
		                "teacherNo": null,
		                "openid": null,
		                "point": null,
		                "userRemark": null,
		                "useType": 1,
		                "schoolName": "测试学校8",
		                "classesName": null,
		                "gradeId": null,
		                "gradeName": null,
		                "phaseName": "初中",
		                "provinceName": "北京市",
		                "cityName": "市辖区",
		                "districtName": "西城区",
		                "subjects": null,
		                "roleName": "校长"
		            }
		        ],
		        "pageNum": 1,
		        "pageSize": 10,
		        "size": 2,
		        "startRow": 1,
		        "endRow": 2,
		        "pages": 1,
		        "prePage": 0,
		        "nextPage": 0,
		        "isFirstPage": true,
		        "isLastPage": true,
		        "hasPreviousPage": false,
		        "hasNextPage": false,
		        "navigatePages": 8,
		        "navigatepageNums": [
		            1
		        ],
		        "navigateFirstPage": 1,
		        "navigateLastPage": 1,
		        "firstPage": 1,
		        "lastPage": 1
		    }
		}
	 *
	 *
	 */
    @RequestMapping(value = "listAllSchoolStudentPage", name = "学生列表", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('/student/listAllSchoolStudentPage')")
    public RestResult getStudentListByClassesId(@RequestParam(name = "schoolId", required = false) Long schoolId,
    		@RequestParam(name = "phaseId", required = false) Long phaseId,
    		@RequestParam(name = "gradeId", required = false) Long gradeId,
    		@RequestParam(name = "classesId", required = false) Long classesId,
    		@RequestParam(name = "userName", required = false) String userName,
    		@RequestParam(name = "account", required = false) String account,
    		@RequestParam(value = "isGraduated", required = false) Integer isGraduated,
    		@RequestParam(name = "pageNum", required = false) Integer pageNum,
			@RequestParam(name = "pageSize", required = false) Integer pageSize)
    		throws Exception {
    	
    	PageInfo<UserVo> pageInfo = userService.getStudentListByClassesId(pageNum, pageSize,schoolId,phaseId, gradeId,classesId,userName,account,isGraduated);
        
        return RestResult.ok(pageInfo);
    }
    
    /**
	 * 保存学生信息
	 *
	 * @apiGroup student
	 * @api {post} /student/save 保存学生信息
	 * @apiVersion 1.0.0
	 * @apiName save
	 *
	 * @apiParam {SysUser} student 学生信息
	 * @apiParamExample 请求示例（json）
	 * {
		    "userName": "张三",
		    "studentNo": "3454463",
		    "phone": "13301234567",
		    "gender": 1,
		    "schoolId": 1,
		    "phaseId": 2,
		    "classesId": 1,
		    "type": 2
		
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "userId": 3
		    }
		}
	 *
	 *
	 */
	@RequestMapping(value = "save", name = "保存学生信息", method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/student/save')")
	public RestResult save(@Valid @RequestBody SysUser student) throws Exception{
		Map<String, Object> result = new HashMap<>();
		
		result = userService.saveStudent(student);
		
		// 统计学校班级、教师、学生数据
		schoolService.updateSchoolStudentNumBySchoolId(student.getSchoolId());
		
		return RestResult.ok(result);
	}
	
	/**
	 * 批量启用或停用
	 *
	 * @apiGroup student
	 * @api {post} /student/batchuse 批量启用或停用
	 * @apiVersion 1.0.0
	 * @apiName batchUse
	 *
	 * @apiParam {Map} dataMap 启用 {"use": 0}  停用 {"use": 1}
	 * @apiParamExample 请求示例（json）
	 * {
		    "studentIds": [2,3,5],
		    "use": 1 
		
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": null
		}
	 *
	 *
	 */
	@RequestMapping(value = "/batchuse", name = "批量启用或停用", method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/student/batchuse')")
	public RestResult batchUse(@RequestBody Map<String,Object> dataMap) throws Exception{
		
		Integer isUse = MapUtils.getInteger(dataMap,"use");
        @SuppressWarnings("unchecked")
		List<String> studentIdList = (List<String>)MapUtils.getObject(dataMap,"studentIds");
        Long[] idList = new Long[]{};
        if(studentIdList != null){
        	idList = new Long[studentIdList.size()];
        	int i = 0 ;
            for (String sId:studentIdList)
            {
            	idList[i]= Long.valueOf(sId);
            	i++;
            }
        }

        userService.batchUse(idList, isUse);
		
		return RestResult.ok();
		
	}
	
	/**
	 * 删除学生
	 * @apiGroup student
	 * @api {post} /student/delete 删除学生
	 * @apiVersion 1.0.0
	 * @apiName deleteUser
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "userId": 2,
		    "schoolId": 1
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
  @RequestMapping(value="/delete" , method = RequestMethod.POST)
  @PreAuthorize("hasAuthority('/student/delete')")
  public RestResult deleteUser(@RequestBody Map<String,Object> dataMap) throws Exception {
  	
	Long userId = MapUtils.getLong(dataMap, "userId");
	Long schoolId = MapUtils.getLong(dataMap, "schoolId");
	
	if (userId == null || userId<=0 || schoolId == null || schoolId<=0 )
	{
		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
	}
		
  	int isOk = userService.deleteUser(userId);
  	if (isOk>0)
		{
  			schoolService.updateSchoolStudentNumBySchoolId(schoolId);
  			
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
  }
	
  	/**
	 * 获取学生信息
	 * @apiGroup student
	 * @api {post} /student/info 获取学生信息
	 * @apiVersion 1.0.0
	 * @apiName getStudent
	 *
	 * @apiParam {Long} studentId 用户id
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "userId": 2,
		        "account": "1111",
		        "userName": "学生1",
		        "pinyin": null,
		        "phone": "13701234567",
		        "phaseId": 2,
		        "schoolId": 1,
		        "classesId": 2,
		        "birthday": null,
		        "gender": "0",
		        "type": 2,
		        "imageUrl": null,
		        "provinceCode": "110000",
		        "cityCode": "110100",
		        "districtCode": "110105",
		        "address": null,
		        "roleId": 4,
		        "intro": null,
		        "studentNo": "1111",
		        "teacherNo": null,
		        "openid": null,
		        "point": null,
		        "userRemark": null,
		        "useType": 0,
		        "schoolName": "测试学校",
		        "classesName": "八年级2班",
		        "gradeId": 8,
		        "gradeName": "八年级",
		        "phaseName": "初中",
		        "provinceName": "北京市",
		        "cityName": "市辖区",
		        "districtName": "朝阳区",
		        "subjects": null,
		        "roleName": "校长"
		    }
		}
	 *
	 *
	 */
	@RequestMapping(value = "info", name = "学生信息", method = RequestMethod.GET)
	@PreAuthorize("hasAuthority('/student/info')")
	public RestResult getStudent(@RequestParam Long studentId) throws Exception{
		UserVo studentVo = null;
		
		studentVo = userService.getUserById(studentId);
		
		return RestResult.ok(studentVo);
	}
	
	/**
	 * 重置密码
	 * @apiGroup student
	 * @api {post} /student/resetpassword 重置密码
	 * @apiVersion 1.0.0
	 * @apiName resetStudentPassword
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "userId": 2
		}
	 *
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
    @RequestMapping(value="/resetpassword", method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('/student/resetpassword')")
    public RestResult resetStudentPassword(@RequestBody Map<String,Object> dataMap) throws Exception {
      	
    	Long userId = MapUtils.getLong(dataMap, "userId");
    	
    	if (userId == null || userId<=0 )
    	{
    		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
    	}
    	
    	int isOk = userService.restUserPassword(userId);
    	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
    }
    
    /**
     * 学生转校或转班
	 *
	 * @apiGroup student
	 * @api {post} /student/move 学生转校或转班
	 * @apiVersion 1.0.0
	 * @apiName studentMove
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "studentIds": [2,3,5],
		    "schoolId": 1,
		    "phaseId": 2,
		    "classesId": 5 
		
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": null
		}
	 *
	 *
	 */
    @RequestMapping(value = "/move",method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('/student/move')")
    public RestResult studentMove(@RequestBody Map<String,Object> dataMap) throws Exception {
    	
        Long schoolId = MapUtils.getLong(dataMap, "schoolId");
        Long phaselId = MapUtils.getLong(dataMap, "phaseId");
        Long classId = MapUtils.getLong(dataMap, "classesId");

        String studentIds = (String)MapUtils.getObject(dataMap,"studentIds");
     	String[] sids = studentIds.split(",");
     	Long[] ids = new Long[sids.length];
     		
 	    for(int i=0;i<sids.length;i++){

 	    	ids[i] = Long.parseLong(sids[i]);

 	    }
 	    
        userService.moveStudents(ids, schoolId, phaselId, classId);
        
        schoolService.updateSchoolStudentNum();
        
        return RestResult.ok();
    }

    /**
     * 学生移出校
	 *
	 * @apiGroup student
	 * @api {post} /student/outschool 学生移出校
	 * @apiVersion 1.0.0
	 * @apiName outSchool
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "studentIds": [2,3,5],
		    "schoolId": 1
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": null
		}
	 *
	 *
	 */
    @RequestMapping(value = "/outschool",method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('/student/outschool')")
    public RestResult outSchool(@RequestBody Map<String,Object> dataMap) throws Exception {
    	
    	Long schoolId = MapUtils.getLong(dataMap, "schoolId");
        String studentIds = (String)MapUtils.getObject(dataMap,"studentIds");
    	String[] sids = studentIds.split(",");
    	Long[] ids = new Long[sids.length];
    		
	    for(int i=0;i<sids.length;i++){

	    	ids[i] = Long.parseLong(sids[i]);

	    }
	    
        userService.outSchool(ids);
        
        schoolService.updateSchoolStudentNumBySchoolId(schoolId);
        
        return RestResult.ok();
    }

    /**
     * 移出班
     *
	 * @apiGroup student
	 * @api {post} /student/outclass 学生移出班
	 * @apiVersion 1.0.0
	 * @apiName outClass
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "studentIds": [2,3,5]
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": null
		}
	 *
	 *
	 */
    @RequestMapping(value = "/outclass",method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('/student/outclass')")
    public RestResult outClass(@RequestBody Map<String,Object> dataMap) throws Exception {
    	
    	String studentIds = (String)MapUtils.getObject(dataMap,"studentIds");
     	String[] sids = studentIds.split(",");
     	Long[] ids = new Long[sids.length];
     		
 	    for(int i=0;i<sids.length;i++){

 	    	ids[i] = Long.parseLong(sids[i]);

 	    }
 	    
        userService.outClasses(ids);

        return RestResult.ok();
    }
    
    /**
	 * 启用学生
	 * 
	 * @apiGroup student
	 * @api {post} /student/on 启用学生
	 * @apiVersion 1.0.0
	 * @apiName onStudent
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "userId": 2
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
    @RequestMapping(value = "/on", method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('/student/on')")
    public RestResult onStudent(@RequestBody Map<String,Object> dataMap) throws Exception {
    	
    	Long userId = MapUtils.getLong(dataMap,"userId");
    	if (userId == null || userId<=0)
    	{
    		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
    	}
    	    			
    	int isOk = userService.useUser(userId,UseTypeEnum.ISUSE.getCode());
    	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
    }
    
  
    /**
	 * 停用学生
	 * @apiGroup student
	 * @api {post} /student/off 停用学生
	 * @apiVersion 1.0.0
	 * @apiName offStudent
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "userId": 2
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": 1
		}
	 *
	 *
	 */
    @RequestMapping(value = "/off", method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('/student/off')")
    public RestResult offStudent(@RequestBody Map<String,Object> dataMap) throws Exception {
    	
    	Long userId = MapUtils.getLong(dataMap,"userId");
    	if (userId == null || userId<=0)
    	{
    		return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
    	}
    	    			
    	int isOk = userService.useUser(userId,UseTypeEnum.NOTUSE.getCode());
    	if (isOk>0)
		{
			return RestResult.ok(isOk);
		}
		else
		{
			return RestResult.error();
		}
    }
    
    
    /**
     * 导入学生
     *
	 * @apiGroup student
	 * @api {post} /student/importstudent 导入学生
	 * @apiVersion 1.0.0
	 * @apiName importStudent
	 *
	 * @apiParam {MultipartFile} file 学生excel文件
	 * @apiParam {Long} schoolId 学校id
	 * @apiParam {HttpServletRequest} request 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": null
		}
	 *
	 *
	 */
	@RequestMapping(value = "importstudent", name = "导入学生", method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('/student/importstudent')")
	public RestResult importStudent(MultipartFile file, 
			@RequestParam(value = "schoolId") Long schoolId, 
										HttpServletRequest request) throws Exception {
		
		Map<String, Object> result = userService.importStudent(file, schoolId, request);

		return RestResult.ok(result);
		
	}


}
